//index.js
// 引入common公共方法
let http = require('../../utils/api.js');
import {
    toData,
    myHttps,
    json,
    login
} from '../../utils/util.js';
import {
    indexTime
} from '../../utils/indexTime.js';
import {
    myHttpss,
} from '../../utils/json.js';
let wxparse = require("../../wxParse/wxParse.js")
//获取应用实例
const app = getApp()
Page({
    data: {
        shareImgSrc: '',
        clickindex: '', //记录点击个数
        clicknumber: '', //收藏个数
        tList: [], //弹框列表
        List: [], //文章列表
        ids: '', // 首页文章列表的id
        first: '', // 首次进入页面的弹窗
        show: false, // 分享窗
        size: 10,
        page: 1,
        hiddenLoading: false,
        code: '',
        id: '', //点谁的分享图标 获取谁的id
        sign: '', //判断是不是第一次进入首页,值为yes得时候说明不是第一次进入首页
        dkcontent: '', //内容区的数据 
        channelid: [], //频道选择的结果的id集合 
        isLogin: '', //是否已经授权
        title: '', //分享页面分享出去的title
        imgs: '', //分享出去的图片
        content: '', //分享朋友圈得内容
        sharess: false, //分享朋友圈弹框
        channelid: [], //选择得频道id
        hideHeader: true,
        hideBottom: true,
        refreshTime: '', // 刷新的时间 
        loadMoreData: '加载更多……' 
    },
    onLoad: function(e) {
        console.log(wx.getStorageSync('no_login'))
        if (wx.getStorageSync('no_login') != 'no') {//没有授权过 或者授权失败
            wx.redirectTo({
                url: '../first/first',
                success: function(res) {},
                fail: function(res) {},
                complete: function(res) {},
            })
        }else {//授权过
            //   请求首页文章列表
            this.indexList(this.data.size, this.data.page);  

        }
        this.setData({
            isLogin: wx.getStorageSync('no_login'),
            sign: wx.getStorageSync('sign'),
            userId: wx.getStorageSync('userId'),
        }) 
        //   请求首页文章列表
        // this.indexList(this.data.size, this.data.page);
        
    },

    // 点赞 文章点赞接口
    showLike: function(e) {
        this.setData({
            hiddenLoading: false
        })
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        // console.log(index)
        let url = http.api.articleGood + id + '/like';
        myHttps({
            url: url,
            method: "POST",
        }).then(res => {
            if (res.code == 1) {
                this.data.List[index].content.like = true
                this.data.List[index].content.like_count = this.data.List[index].content.like_count + 1
                this.setData({
                    List: this.data.List,
                    hiddenLoading: true
                });
            }
        }).catch(err => {})
    },
    // 文章取消点赞  接口
    showLikeno: function(e) {
        this.setData({
            hiddenLoading: false
        })
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        // console.log(index)
        let url = http.api.articleGood + id + '/like';
        myHttps({
            url: url,
            method: "DELETE",
        }).then(res => {
            // console.log(res)
            if (res.code == 1) {
                this.data.List[index].content.like = false
                this.data.List[index].content.like_count = this.data.List[index].content.like_count - 1
                this.setData({
                    List: this.data.List,
                    hiddenLoading: true
                });
            }
        }).catch(err => {})
    },
    // 文章击收藏 接口
    collect(e) {
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        let url = http.api.collects + id + '/fav';
        myHttps({
            url: url,
            method: "POST",
        }).then(res => {
            if (res.code == 1) {
                this.data.List[index].content.fav = true
                this.data.List[index].content.fav_count = this.data.List[index].content.fav_count + 1
                this.setData({
                    List: this.data.List
                })
            }
        }).catch(err => {})
    },
    // 文章取消收藏
    cancelcollect(e) {
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        let url = http.api.collects + id + '/fav';
        myHttps({
            url: url,
            method: "DELETE",
        }).then(res => {
            if (res.code == 1) {
                this.data.List[index].content.fav = false
                this.data.List[index].content.fav_count = this.data.List[index].content.fav_count - 1
                this.setData({
                    List: this.data.List
                })
            }
        }).catch(err => {})
    },
    //解读点赞接口
    showLikes: function(e) {
        this.setData({
            hiddenLoading: false
        })
        let id = e.currentTarget.dataset.id //解读id
        let index = e.currentTarget.dataset.index
        let url = http.api.reviewGood + id + '/like';
        myHttps({
            url: url,
            method: "POST",
        }).then(res => {
            if (res.code == 1) {
                this.data.List[index].content.like = true
                this.data.List[index].content.like_count = this.data.List[index].content.like_count + 1
                this.setData({
                    List: this.data.List,
                    hiddenLoading: true
                });
            }
        }).catch(err => {})
    },
    // 解读取消点赞  接口
    showLikenos: function(e) {
        this.setData({
            hiddenLoading: false
        })
        let id = e.currentTarget.dataset.id //解读id
        let index = e.currentTarget.dataset.index
        let url = http.api.reviewGood + id + '/like';
        myHttps({
            url: url,
            method: "DELETE",
        }).then(res => {
            if (res.code == 1) {
                this.data.List[index].content.like = false
                this.data.List[index].content.like_count = this.data.List[index].content.like_count - 1
                this.setData({
                    List: this.data.List,
                    hiddenLoading: true
                });
            }
        }).catch(err => {})
    },
    // 解读点击收藏 接口
    collects(e) {
        let id = e.currentTarget.dataset.id //解读id
        let index = e.currentTarget.dataset.index
        let url = http.api.reviewcollect + id + '/fav';
        myHttps({
            url: url,
            method: "POST",
        }).then(res => {
            if (res.code == 1) {
                this.data.List[index].content.fav = true
                this.data.List[index].content.fav_count = this.data.List[index].content.fav_count + 1
                this.setData({
                    List: this.data.List,
                    hiddenLoading: true
                })
            }
        }).catch(err => {})
    },
    // 解读取消收藏
    cancelcollects(e) {
        let id = e.currentTarget.dataset.id //解读id
        let index = e.currentTarget.dataset.index
        let url = http.api.reviewcollect + id + '/fav';
        myHttps({
            url: url,
            method: "DELETE",
        }).then(res => {
            if (res.code == 1) {
                this.data.List[index].content.fav = false
                this.data.List[index].content.fav_count = this.data.List[index].content.fav_count - 1
                this.setData({
                    List: this.data.List,
                    hiddenLoading: true
                })
            }
        }).catch(err => {})
    },
    // 选择领域结果  提交选择频道接口
    selected() {
        let userId = wx.getStorageSync('userId');
        var channelid = [];
        for (var i = 0; i < this.data.tList.length; i++) {
            if (this.data.tList[i].show == false) {
                // console.log(channel[i].id)
                channelid.push(this.data.tList[i].id)
            }
        }
        let url = http.api.selected + userId + '/channels';
        let obj = {
            channel_id: channelid
        }
        this.setData({
            channelid: channelid
        })
        myHttpss({
            url: url,
            method: 'POST',
            data: obj
        }).then(res => {})
    },
    //   跳到文章详情页
    goDetails(e) {
        // console.log(e)
        let id = e.currentTarget.dataset.id;
        let contents = e.currentTarget.dataset.contents;
        wx.navigateTo({
            url: '../details/details?id=' + id + '&content=' + contents
        });
    },
    //跳解读详情
    goReviewDetails(e) {
        let id = e.currentTarget.dataset.id;
        let contents = e.currentTarget.dataset.contents;
        wx.navigateTo({
            url: '../unscrambleDetails/unscrambleDetails?id=' + id + '&content=' + contents
        });
    },
    // 跳转到媒体主页
    goMediaHome(e) {
        let platform_id = e.currentTarget.dataset.platformid
        if (platform_id == 1) {
            let id = e.currentTarget.dataset.id; //媒体id
            wx.navigateTo({
                url: '../mediaHome/mediaHome?id=' + id,
                success: function(res) {},
                fail: function(res) {},
                complete: function(res) {},
            })
        }
    },
    //   跳到主题主页
    gothemeHome(e) {
        // console.log(e)
        var id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../themeHome/themeHome?id=' + id
        });
    },
    //下拉刷新从新初始化页码,条数
    onPullDownRefresh: function() {
        //下拉三个点消失
        wx.stopPullDownRefresh();
        var date = new Date();
        this.setData({
            hiddenLoading: false,
            size: 10,
            page: 1,
            // refreshTime: date.toLocaleTimeString(),
            // hideHeader: false
        })
        this.indexList(this.data.size, this.data.page,'xia');
    },
    // 上拉加载数据
    onReachBottom: function() {
        this.setData({
            size: 10,
            page: this.data.page + 1,
        })
        this.indexList(this.data.size, this.data.page);
    },
    // 请求首页文章
    indexList(size, page, xia) {
        
        let url = http.api.minsList + '?size=' + size + '&page=' + page;
        myHttps({
            url: url,
            method: "GET"
        }).then(res => {
            if (res.code == 1) {
                // console.log(res.data.content)
                if (xia) {
                    for (var i = 0; i < res.data.content.length; i++) {
                        res.data.content[i].content.update_time = indexTime(res.data.content[i].content.update_time)
                        res.data.content[i].content.pubdate = indexTime(res.data.content[i].content.pubdate)
                    }
                    this.data.List = res.data.content
                }else {
                    for (var i = 0; i < res.data.content.length; i++) {
                        res.data.content[i].content.update_time = indexTime(res.data.content[i].content.update_time)
                        res.data.content[i].content.pubdate = indexTime(res.data.content[i].content.pubdate)
                        this.data.List.push(res.data.content[i])
                    }
                }
                // console.log(this.data.List)
                this.setData({
                    List: this.data.List,
                    hiddenLoading: true,
                    // hideHeader: true
                })
                // console.log(this.data.List)
            } else if (wx.getStorageSync('no_login') == 'no' &&res.code == 401){
                wx.showModal({
                    title: '抱歉',
                    content: '授权过期,请重新登陆',
                    confirmText: '确定',
                    showCancel: false,
                    success: function (res) {
                        console.log(res.confirm)
                        if (res.confirm) {
                            wx.redirectTo({
                                url: '../first/first'
                            })
                        }
                    }
                })
            }
        }).catch(err => {})
    },
    // 分享 页面
    onShareAppMessage: function(options) {　
        var that = this;
        // 设置菜单中的转发按钮触发转发事件时的转发内容　
        if (options.target.dataset.types == "Review") { //解读分享
            // console.log(options.target.dataset)
            if (options.from == 'button') {
                var eData = options.target.dataset;
                // console.log(eData)
                return {
                    title: eData.title,
                    imageUrl: eData.img,
                    path: '/pages/unscrambleDetails/unscrambleDetails?id=' + eData.id
                }
            }
        } else { //文章和转载分享
            // console.log(options.target.dataset)
            var shareObj = {
                // title: eData.title,
                // path: '/pages/details/details?id=' + eData.id,
                // imageUrl: eData.img,//不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4 　　
            }
            // 来自页面内的按钮的转发　
            if (options.from == 'button') {
                var eData = options.target.dataset;
                return {
                    title: eData.title,
                    imageUrl: eData.img,
                    path: '/pages/details/details?id=' + eData.id
                }
            }
            return shareObj; // 返回shareObj
        }

    },
    // 点击分享图标弹窗 
    // showss(e) {
    //     // console.log(e)
    //     this.setData({
    //         imgs: e.currentTarget.dataset.img,
    //         title: e.currentTarget.dataset.title,
    //         clicknumber: e.currentTarget.dataset.value,
    //         clickindex: e.currentTarget.dataset.index,
    //         id: e.currentTarget.dataset.id,
    //         content: e.currentTarget.dataset.content,
    //         show: true
    //     });
    // },
    // 弹窗取消的点击事件
    cancel() {
        this.setData({
            show: false
        });
    },
    // 绘制图片
    onShowss() {
        console.log(this.data.title)
        console.log(this.data.content)
        //2. canvas绘制文字和图片
        const ctx = wx.createCanvasContext('myCanvas');
        var imgPath = '../../images/Bitmaphhhh.png'
        var bgImgPath = '../../images/diban.png';
        ctx.drawImage(imgPath, 0, 0, 600, 520);

        ctx.setFillStyle('white')
        ctx.fillRect(0, 520, 600, 280);

        // ctx.drawImage(imgPath, 0, 0, 42,42);
        ctx.drawImage(bgImgPath, 0, 0, 600, 500);
        ctx.drawImage(imgPath, 20, 110, 40, 30);

        ctx.setFontSize(12)
        ctx.setFillStyle('#000000')
        // ctx.fillText(this.data.title, 20, 20,200)
        this.drawText(ctx, this.data.title, 20, 20, 300, 250);

        ctx.setFontSize(10)
        ctx.setFillStyle('#616161')
        this.drawText(ctx, this.data.content, 20, 50, 300, 250);

        ctx.setFontSize(6)
        ctx.fillText('长按小程序码，阅读详情', 70, 123)
        ctx.setFontSize(6)
        ctx.fillText('来自「 数字奇迹 」', 70, 133)
        ctx.draw()
    },
    // 文字换行
    drawText: function(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
        var lineWidth = 0;
        var lastSubStrIndex = 0; //每次开始截取的字符串的索引
        for (let i = 0; i < str.length; i++) {
            lineWidth += ctx.measureText(str[i]).width;
            if (lineWidth > canvasWidth) {
                ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
                initHeight += 12; //字体的高度
                lineWidth = 0;
                lastSubStrIndex = i;
                titleHeight += 30;
            }
            if (i == str.length - 1) { //绘制剩余部分
                ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
            }
        }
        // 标题border-bottom 线距顶部距离
        titleHeight = titleHeight + 10;
        return titleHeight
    },

    // 弹窗分享到朋友圈
    Shares() {
        // this.setData({
        //     hiddenLoading: false,
        // })
        wx.showLoading({
            title: '努力生成中...'
        })
        this.onShowss()
        // 3. canvas画布转成图片
        var that = this;
        setTimeout(function() {
            wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                // width: 400,
                // height: 400,
                destWidth: 600,
                destHeight: 400,
                canvasId: 'myCanvas',
                quality: 0,
                success: function(res) {
                    // console.log(res.tempFilePath);
                    that.setData({
                        shareImgSrc: res.tempFilePath,
                        // hiddenLoading:true,
                    })
                    wx.hideLoading()
                },
                fail: function(res) {
                    console.log(res)
                }
            })
        }, 3000)
        this.setData({
            show: false
        })
        this.setData({
            sharess: true
        })

        // this.downloadImage()
        // wx.navigateTo({
        //     url: '../picture/picture?title='+this.data.title+'&content='+this.data.content+'&id='+ this.data.id,
        // })
    },
    // 保存图片到相册
    baocun() {
        //4. 当用户点击分享到朋友圈时，将图片保存到相册
        var that = this;
        wx.saveImageToPhotosAlbum({
            filePath: that.data.shareImgSrc,
            success(res) {
                wx.showModal({
                    title: '存图成功',
                    content: '图片成功保存到相册',
                    showCancel: false,
                    confirmText: '确定',
                    confirmColor: '#72B9C3',
                    success: function(res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                        }
                        that.hideShareImg()
                    }
                })
            }
        })

    },
    // 点击叉号关闭弹框
    closess() {
        this.setData({
            sharess: false
        })
    },
    //点击生成下载海报
    // downloadImage() {
    //     let _this = this
    //     // 获取qrCode
    //     // let url = http.api.qrcode + encodeURIComponent('/pages/candyDetail/candyDetail?skuId=' + _this.data.model.id + '&userId=' + _this.props.userStore.userInfo.id + '&channel=friendShare')
    //      let url = '../../images/Bitmaphhhh.png'
    //     // // console.log(url)
    //     // wx.downloadFile({
    //     //     url: url,
    //     //     success(res) {
    //     //         console.info(res)
    //     //         console.log('开始绘制图片')
    //     //         console.log(res.tempFilePath)
    //     //         _this.myCanvasEvent(res.tempFilePath);
    //     //     }
    //     // })
    //     _this.myCanvasEvent(url);
    // },
    // // 生成海报
    // myCanvasEvent(qrCode) {
    //     console.log(qrCode)
    //     let _this = this;
    //     let windowWidth = _this.data.windowWidth;
    //     let bgPath = '../../images/bgbg.png';
    //     let comImg = qrCode
    //     let title = _this.data.title
    //     let content = _this.data.content
    //     const ctx = wx.createCanvasContext('myCanvas')
    //     const downloadTask = wx.downloadFile({
    //         url: comImg,
    //         success(res) {
    //             console.log(res)
    //             //绘制背景图片
    //             ctx.drawImage(bgPath, 0, 0, 320, 320);
    //             ctx.setFillStyle('white');
    //             ctx.stroke();
    //             ctx.drawImage(res.tempFilePath, 80, 20, 165, 165)
    //             ctx.setFontSize(14);
    //             ctx.setTextAlign('center');
    //             ctx.fillText('帮我抢 【' + title + '】', 170, 205);
    //              ctx.drawImage(qrCode, 220, 220, 70, 70)
    //             ctx.draw();
    //         }
    //     })
    //     downloadTask.onProgressUpdate(res => {
    //         console.info('downloadTask', res)
    //         if (res.totalBytesExpectedToWrite === res.totalBytesWritten) {
    //             let _this = this
    //             setTimeout(() => {
    //                 _this.canvasToImage()
    //             }, 500)
    //         }
    //     })

    // },
    // // 转化成图片
    // canvasToImage() {
    //     let _this = this;
    //     let windowWidth = _this.data.windowWidth;
    //     wx.canvasToTempFilePath({
    //         x: 0,
    //         y: 0,
    //         width: 320,
    //         height: 320,
    //         destWidth: 1200,
    //         destHeight: 1200,
    //         canvasId: 'myCanvas',
    //         fileType: 'png',
    //         quality: '1',
    //         success(res) {
    //             console.log('朋友圈分享图生成成功:' + res.tempFilePath)
    //             let tempFilePath = res.tempFilePath
    //             _this.setData({
    //                 canvasImg: tempFilePath
    //             })
    //             wx.getSetting({
    //                 success(res) {
    //                     console.log('朋友圈分享图生成成功:' + JSON.stringify(res))
    //                     if (res.authSetting['scope.writePhotosAlbum']) {
    //                         wx.saveImageToPhotosAlbum({
    //                             filePath: tempFilePath,
    //                             success(res2) {
    //                                 _this.setData({
    //                                     checkShare: false,
    //                                     goFriend: true,
    //                                 })
    //                             }
    //                         })
    //                     } else {
    //                         wx.authorize({
    //                             scope: 'scope.writePhotosAlbum',
    //                             success: function (res) {
    //                                 console.log(res)
    //                             }, fail: function (res) {
    //                                 wx.showModal({
    //                                     title: '重要提示',
    //                                     content: '需要授权才可保存图片',
    //                                     success: function (res) {
    //                                         wx.openSetting({
    //                                             success: function (res) {
    //                                                 console.log(res)
    //                                             }
    //                                         })
    //                                     }
    //                                 })

    //                             }
    //                         })


    //                     }
    //                 }
    //             })
    //         },
    //         fail(err) {
    //             console.log('失败')
    //             console.log(err)
    //         }
    //     })
    // },
})